import threading
import time
from threading import Thread, Lock

#1 由于线程之间数据共享，即随机的执行顺序，将带来安全问题，如下案例
# 两个、或者三个线程可能同时出售同一张票
ticket = 50
def sale_ticket():
    global ticket
    for i in range(100):
        if ticket > 0:
            print(f'{threading.current_thread().name}正在出售第{ticket}张票')
            ticket -= 1
        time.sleep(1)

if __name__ == '__main__':
    for i in range(3):
        t = Thread(target=sale_ticket)
        t.start()

#2 使用Lock锁-解决数据共享带来的安全问题
ticket2 = 50
Lock_obj = Lock()   # 创建Lock锁
def sale_ticket2():
    global ticket2
    for i in range(100):
        Lock_obj.acquire()      # 锁住判断，即判断不结束，下一个线程无法进入
        if ticket2 > 0:
            print(f'{threading.current_thread().name}正在出售第{ticket2}张票')
            ticket2 -= 1
        time.sleep(1)
        Lock_obj.release()      # Lock锁释放

if __name__ == '__main__':
    for i in range(3):
        t = Thread(target=sale_ticket2)
        t.start()